// pages/operation-center/edit-staff/index.js
const app = getApp()
Page({
  data: {
    expand: false,
    showTypeSelector: false,
    departmentList: [
      { id: 0, name: '' },
      { id: 1, name: '联创优科' },
      { id: 2, name: '技术部' },
      { id: 3, name: '业务部' },
      { id: 4, name: '销售部' },
      { id: 5, name: '财务部' },
    ],
    currentType: 0,
    currentTypeName: '',
    maxDate: new Date().getTime(),
    minDate: new Date(2010, 1, 1).getTime(),
    staffInfo: {
      name: '',
      departmentid: null,
      departmentName: null,
      zauserid: '',
      zaphone: '',
      inctime: 0,
      inctimeText: ''
    },
    action: 'add',
    showTime: '',
    title:'添加员工'
  },
  onLoad(option) {
    this.getDepartmentList(option.id)
  },
  getDepartmentList(id) {
    app.axios(
      'user',
      {
        op: 'ajaxDepLists',
      }
    ).then(res => {
      if (res.code) {
        this.setData({
          departmentList: res.lists
        })
        if (id) {
          this.getUserInfo(id)
          this.setData({
            action: 'edit',
            title:'编辑员工'
          })
        }
      }
    })
  },
  getUserInfo(id) {
    app.axios(
      'user',
      {
        op: 'ajaxUserDlDetail',
        id: id
      }
    ).then(res => {
      if (res.code) {
        this.setData({
          staffInfo: res.item
        })
      }
    })
  },
  navigateTo(e) {
    app.navigateTo(e.currentTarget.dataset.url, e.currentTarget.dataset.type)
  },
  toggleExpand() {
    this.setData({ expand: !this.data.expand })
  },
  toggleTypeSelector() {
    this.setData({ showTypeSelector: !this.data.showTypeSelector })
  },
  changeType(e) {
    const id = e.currentTarget.dataset.id;
    // 从 departmentList 中查找匹配的项
    const selectedType = this.data.departmentList.find(item => item.id === id);
    if (selectedType) {
      this.setData({
        'staffInfo.departmentid': id,
        'staffInfo.departmentName': selectedType.name // 同步更新名称
      });
    }
  },
  noEditable() {
    wx.showToast({
      title: '不可修改',
      icon: 'none',
    })
  },
  toggleDateSelector() {
    // 直接调用组件方法（需获取实例）
    const drawer = this.selectComponent('#v-drawer-date')
    drawer.toggleDrawer()

  },
  onDateConfirm(e) {
    this.toggleDateSelector()
    this.setData({
      'staffInfo.inctime': app.dateFormatter(e.detail),
      showTime: app.dateFormatter(e.detail),
    })
  },
  handleInputChange(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    this.setData({
      [`staffInfo.${field}`]: value
    })
  },
  submit() {
    const parmas = this.data.staffInfo
    console.log(parmas, 'parmas')
    const op = 'ajaxUserDlAdd'
    parmas.op = op
    app.axios(
      'user',
      parmas
    ).then(res => {
      if(res.code){
        wx.showToast({
          title:'修改成功'
        })
        setTimeout(() => {
          app.navigateTo('/pages/operation-center/index/index?activeTab=2')
        }, 1500);
      }
    })
  }
})